﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AteneoLibriBusinessLogic.Entities;

namespace AteneoLibri.Account
{
    public partial class Dashboard : System.Web.UI.Page
    {

        User user = null;

        protected void Page_Load(object sender, EventArgs e)
        {
            user = Utility.HttpSessionManager.GetWebUser();
            if (user != null)
            {
                if (user.LastAccess.HasValue)
                {
                    ltlLastAccess.Text = "Ultimo accesso: " + user.LastAccess.Value.ToLongDateString() + " alle " + user.LastAccess.Value.ToLongTimeString();
                }
                else
                {
                    ltlLastAccess.Text = "Primo accesso";
                }


                using (wsAteneoLibri.AteneoLibriServiceClient service = new wsAteneoLibri.AteneoLibriServiceClient())
                {
                    // Una volta entrato aggiorno l'ultimo accesso
                    user.LastAccess = DateTime.Now;
                    service.modifyUserAccessDate(user);
                }

                LoadPersonalLibrary();
                LoadSoldBooks();
                LoadPurchasedBook();
            }
            else
            {
                // Redirect per sessione scaduta
                Response.Redirect("~/Logout.aspx");
            }
            
        }        

        /// <summary>
        /// Carico la libreria personale comprendente i libri messi in vendita esclusi quelli venduti.
        /// </summary>
        private void LoadPersonalLibrary()
        {
            using (wsAteneoLibri.AteneoLibriServiceClient service = new wsAteneoLibri.AteneoLibriServiceClient())
            {
                List<Book> myBooks = service.getBooksByIdUser(user.IdUser).Where(x => !x.IsDeleted.HasValue || (x.IsDeleted.HasValue && x.IsDeleted == false)).ToList(); // filtro quelli che hanno il flag IsDeleted a NULL oppure hanno false
                List<Book> myLibrary = new List<Book>();
                foreach (var item in myBooks)
                {
                    bool isBookSold = service.getSalesByBookId(item.IdBook).Where(x => x.EndDate != null).Count() > 0;
                    if (!isBookSold) // se il libro non è stato venduto
                    {
                        myLibrary.Add(item);
                    }
                }

                int trimTitleLength = Convert.ToInt16(System.Configuration.ConfigurationManager.AppSettings["TrimTitleValue"]);
                myLibrary = myLibrary.Select(b => new Book { IdBook = b.IdBook, Title = Utility.Utility.TrimTitle(b.Title, trimTitleLength), Author = b.Author, SellingPrice = b.SellingPrice, UserName = b.UserName, InsertDate = b.InsertDate }).ToList();

                dlLibrary.DataSource = myLibrary;
                dlLibrary.DataBind();

                dlLibraryPortrait.DataSource = myLibrary;
                dlLibraryPortrait.DataBind();

                if (myLibrary.Count() > 0)
                    lblEmptyLibrary.Visible = false;                                       
                else
                    lblEmptyLibrary.Visible = true;
            }
        }

        private void LoadSoldBooks()
        {
            using (wsAteneoLibri.AteneoLibriServiceClient service = new wsAteneoLibri.AteneoLibriServiceClient())
            {
                List<Book> myBooks = service.getBooksByIdUser(user.IdUser);
                List<Book> mySoldBooks = new List<Book>();
                foreach (var item in myBooks)
                {
                    bool isBookSold = service.getSalesByBookId(item.IdBook).Where(x => x.EndDate != null).Count() > 0;
                    if (isBookSold) // se il libro è stato venduto
                    {
                        mySoldBooks.Add(item);
                    }
                }

                if (mySoldBooks.Count() > 0)
                {
                    dlSoldBooks.DataSource = mySoldBooks;
                    dlSoldBooks.DataBind();

                    dlSoldBooksPortrait.DataSource = mySoldBooks;
                    dlSoldBooksPortrait.DataBind();
                }
            }
        }

        private void LoadPurchasedBook()
        {
            using (wsAteneoLibri.AteneoLibriServiceClient service = new wsAteneoLibri.AteneoLibriServiceClient())
            {
                List<Sale> sales = service.getSalesByUserId(user.IdUser);
                List<Book> myPurchasedBooks = new List<Book>();

                foreach (var item in sales)
                {
                    if (item.EndDate != null && (item.SoldTo.HasValue && item.SoldTo.Value)) // controllo se il libro è stato venduto a me
                    {
                        Book book = service.getBookById(item.BookId.Value);
                        myPurchasedBooks.Add(book);
                    }
                    
                }
                
                if (myPurchasedBooks.Count() > 0)
                {
                    dlPurchasedBook.DataSource = myPurchasedBooks;
                    dlPurchasedBook.DataBind();

                    dlPurchasedBookPortrait.DataSource = myPurchasedBooks;
                    dlPurchasedBookPortrait.DataBind();
                }
            }
        }

        protected void btnDetails_Click(object sender, ImageClickEventArgs e)
        {
            ImageButton button = sender as ImageButton;
            string idBook = button.CommandArgument;
            Response.Redirect("~/BookDetails.aspx?IdBook=" + idBook);
        }
    }
}